﻿//操作webservice数据库的相关程序
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using CommonTools;
using System.Threading;
using BusinessServer;
using System.Runtime.InteropServices;
using NS_MyUdpServer;

namespace BusinessCloud
{
    public partial class MainForm : Form
    {
        public static DataTable qjdt = null;//远程服务端登陆返回的dt
        public static byte[] ids = null;//远程服务器ids
        public static WebService.MyService myService = null;//远程服务器的url
        byte[] ids1 = null;
        WebService.WebSlected[] sd1 = null;
        MyUdpServer udpServer;

        private void InitWebService()
        {
            try
            {
                //创建UDP服务器
                udpServer = new MyUdpServer();
                udpServer.UE_LogHandle += new MyUdpServer.LogHandle(log);
                udpServer.Start();

                //登陆远程服务器
                myService = new WebService.MyService();
                myService.Url = System.Configuration.ConfigurationManager.AppSettings["webServiceUrl"];//远程webserver的url
                SqlHelp sqlHelp = new SqlHelp();
                string userName = System.Configuration.ConfigurationManager.AppSettings["loginSerName"];//远程webserver登陆用户名
                string userPwd = System.Configuration.ConfigurationManager.AppSettings["loginSerPwd"];//远程webserver登陆用户名
                WebService.WebSlected[] sd = myService.Login(userName, userPwd, "0");
                if (sd.Length > 0)
                {
                    qjdt = sqlHelp.SlectedsToDataSet(sd).Tables[0];
                    if (qjdt.TableName.ToString().ToLower() != "error")
                    {
                        ids = (byte[])qjdt.Rows[0]["ids"];
                    }
                }
                DataTable idsdt1 = new DataTable(); //ids秘钥
                idsdt1.TableName = "DT635986685815214902";
                ids1 = sqlHelp.GetBinaryFormatData(idsdt1);//将dt转为二进制

                //WebService.MyService webservice = new WebService.MyService();
                sd1 = new WebService.WebSlected[0];//接收服务端返回的结果
                log("启动WebService服务器接口程序");

            }
            catch (Exception ex)
            {
                log(ex.Message + "\n" + ex.StackTrace);

            }

        }

        private void ProcessWebMessage()
        {
            if (MyUdpServer.listRecv.Count > 0)
            {
                //*[;1100;99;636017781943698365;130;100;hello;2016-08-08 19:47:12.100;]
                string message = MyUdpServer.listRecv.Dequeue();//
                string[] messages = message.Split(';');

                if (messages[1] == "1100")//1100是电梯黑匣子故障信息 黑匣子类型为0  *[;1100;流水号;电梯注册代码码;电梯救援识别码;故障代码;故障描述;最后动作时间]
                {
                    log(messages[1] + "黑匣子故障信息");
                    if (messages.Length < 9)
                    {
                        log("命令长度不足：[" + messages.Length + "]");
                        return;
                    }

                    string sbsj = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    try
                    {
                        MessageDB.InsertBlackBox(ids, myService, messages[3], messages[4], "[" + messages[5] + "]" + messages[6], sbsj, messages[7], "0", "", "", "");
                    }
                    catch (Exception ex)
                    {
                        log(ex.Message + "\n" + ex.StackTrace);
                    }
                }

                else if (messages[1] == "2101")//*[;2101;流水号;结果码;结果描述;]
                {
                    log(messages[1] + "远程查看命令的回应");
                    if (messages.Length < 5)
                    {
                        log("命令长度不足：[" + messages.Length + "]");
                        return;
                    }
                    SendMsgToUser(1, message);
                }

                else if (messages[1] == "2200")//*[;2200;流水号;电梯注册代码;电梯救援码;用户刷卡的卡号;]
                {
                    log(messages[1] + "用户刷卡");
                    if (messages.Length < 7)
                    {
                        log("命令长度不足：[" + messages.Length + "]");
                        return;
                    }

                    try
                    {
                        MessageDB.insertLeaderFlushCard(ids, myService, messages[3], messages[4], messages[5]);
                    }
                    catch (Exception ex)
                    {
                        log(ex.Message + "\n" + ex.StackTrace);
                    }
                }

                else if (messages[1] == "2300")//大屏断电  *[;2300;流水号;电梯注册代码;电梯救援码;最后动作类型;最后动作时间;]
                {
                    log(messages[1] + "大屏断电");
                    if (messages.Length < 8)
                    {
                        log("命令长度不足：[" + messages.Length + "]");
                        return;
                    }

                    string sbsj = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    try
                    {
                        MessageDB.InsertBlackBox(ids, myService, messages[3], messages[4], "", sbsj, messages[6], "1", messages[5], "", "");

                    }
                    catch (Exception ex)
                    {
                        log(ex.Message + "\n" + ex.StackTrace);
                    }
                }

                else if (messages[1] == "2310")//大屏来电  *[;2310;流水号;电梯识别码;电梯救援码;恢复供电时间;]
                {
                    log(messages[1] + "大屏来电");
                    if (messages.Length < 7)
                    {
                        log("命令长度不足：[" + messages.Length + "]");
                        return;
                    }

                    string sbsj = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    try
                    {
                        MessageDB.InsertBlackBox(ids, myService, messages[3], messages[4], "", sbsj, messages[5], "2", "", "", "");
                    }
                    catch (Exception ex)
                    {
                        log(ex.Message + "\n" + ex.StackTrace);
                    }
                }

                else if (messages[1] == "2320")//心跳包异常*[;2320;流水号;电梯注册码;电梯救援码;最后心跳包时间;最后动作类型;最后动作时间;最后电源标识;]
                {
                    log(messages[1] + "心跳包异常");
                    string sbsj = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    try
                    {
                        MessageDB.InsertBlackBox(ids, myService, messages[3], messages[4], "", sbsj, messages[7], "3", messages[6], messages[5], messages[8]);
                    }
                    catch (Exception ex)
                    {
                        Console.Out.WriteLine(ex.Message);
                    }
                }

                else if (messages[1] == "2400")//六码绑定  *[;2400;流水号;电梯注册代码;电梯救援识别码;ID卡号;NFC卡号;二维码;电梯硬件编码;经度;纬度;操作员;serverIp;serverPort;]
                {                                 //  0    1     2         3           4            5       6      7        8         9   10   11
                    log(messages[1] + "六码绑定");
                    string rs = messages[0] + ";" + messages[1].Substring(0, 3) + "1;" + messages[2] + ";";

                    if (messages.Length < 12)
                    {
                        log("命令长度不足：[" + messages.Length + "]");
                        rs += "ERROR;命令长度不足;]";
                        udpServer.SendMsg(rs);
                        return;
                    }

                    try
                    {
                        //可以一次添加一个；也可以一次添加多个
                        WebService.WebInsertElevators[] ies = new WebService.WebInsertElevators[1];
                        WebService.WebInsertElevators ie = new WebService.WebInsertElevators();
                        ie.dtjysbm = messages[4];
                        ie.bs = "0"; //表示厂家
                        ie.CPUbm = messages[8];
                        ie.dtzcdm = messages[3];
                        ie.EWMbm = messages[7];
                        ie.NFCbm = messages[6];
                        ie.RFIDbm = messages[5];
                        ie.lat = float.Parse(messages[10]);
                        ie.lng = float.Parse(messages[9]);
                        ie.ryxx = messages[11];
                        if (messages.Length > 12)
                        {
                            ie.bkptip = messages[12];
                            ie.bkptport = cs_common.String2Int(messages[13]);
                        }
                        else
                        {
                            ie.bkptip = "127.0.0.1";
                            ie.bkptport = 80;
                        }
                        ies[0] = ie;
                        sd1 = myService.InsertElevatorInfo(ids1, ies);//调用接口InsertElevatorInfo（秘钥，添加电梯类数组）
                        //*[;2500;流水号;电梯注册码;电梯救援码;电梯所在省份;电梯所在城市; 电梯所在地区;电梯安装地址;经度;纬度;登记机关;使用管理责任单位;使用单位设备编号;制造单位;维保单位;检验单位;下次检验日期;应急救援电话;]
                        rs += "OK;;]";
                        udpServer.SendMsg(rs);

                        Send2500Order(messages[3]);

                    }
                    catch (Exception ex)
                    {
                        rs += "ERROR;" + ex.Message + ";]";
                        udpServer.SendMsg(rs);

                        log(ex.Message + "\n" + ex.StackTrace);
                    }
                }

                else if (messages[1] == "3100")//Gps 轨迹传入数据库[;3100;6666;11111;经度;纬度;人员ID]
                {//*[;3100;6666;636033381574537386;123.2231111000000000;25.1210001000000000;;]
                    log(messages[1] + "Gps轨迹");
                    if (messages.Length < 8)
                    {
                        log("命令长度不足：[" + messages.Length + "]");
                        return;
                    }

                    string gxrq = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    try
                    {
                        MessageDB.insertCapTrack(ids, myService, "9250", "636062829888307169", messages[4], messages[5], gxrq, messages[6], messages[3]);
                    }
                    catch (Exception ex)
                    {
                        log(ex.Message + "\n" + ex.StackTrace);
                    }
                }

                else if (messages[1] == "3200")//救援事件和帽子绑定*[;3200;555;帽子编号;事件ID;人员ID]
                {
                    log(messages[1] + "救援事件和帽子绑定");
                    if (messages.Length < 7)
                    {
                        log("命令长度不足：[" + messages.Length + "]");
                        return;
                    }

                    string sbsj = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    try
                    {
                        MessageDB.insertEventAndCap(ids, myService, "9250", "636062829888307169", messages[4], messages[3], sbsj, "0", messages[5]);
                    }
                    catch (Exception ex)
                    {
                        log(ex.Message + "\n" + ex.StackTrace);
                    }
                }

            }
        }
        /// <summary>
        /// 查找电梯合格证信息并发送2500命令
        /// </summary>
        /// <param name="dtzcdm"></param>
        private void Send2500Order(string dtzcdm)
        {
            DataTable dtElevator = MessageDB.GetElevatorInfo(ids, myService, dtzcdm);
            if (dtElevator.Rows.Count > 0)
            {
                DataTable dt = MessageDB.GetAllUp(ids, myService, dtElevator.Rows[0]["ts_qx_id"].ToString());
                string order_2500 = "*[;2500;" + cs_common.GetSerialNo() + ";" + dtElevator.Rows[0]["dtzcdm"].ToString() + ";" + dtElevator.Rows[0]["dtjysbm"].ToString() + ";" + dt.Rows[1]["qxmc"].ToString() + ";" + dt.Rows[2]["qxmc"].ToString() + ";" + dt.Rows[3]["qxmc"].ToString() + ";" + dtElevator.Rows[0]["dtwz"].ToString() + ";" + dtElevator.Rows[0]["longitude"].ToString() + ";" + dtElevator.Rows[0]["latitude"].ToString() + ";" + dtElevator.Rows[0]["zgjgmc"].ToString() + ";" + dtElevator.Rows[0]["sydwmc"].ToString() + ";" + dtElevator.Rows[0]["dtwz"].ToString() + ";" + dtElevator.Rows[0]["cjmc"].ToString() + ";" + dtElevator.Rows[0]["wbdwmc"].ToString() + ";" + dtElevator.Rows[0]["jydwmc"].ToString() + ";" + dtElevator.Rows[0]["xcjyrq"].ToString() + ";" + "" + ";]";
                udpServer.SendMsg(order_2500);
            }
        }

        //根据救援识别码查询到该终端所属服务器ip:port
        private string GetServerIP(string rescueCode)
        {
            DataTable dt = MessageDB.GetElevatorInfo(ids, myService, rescueCode);
            string bkptip = dt.Rows[0]["bkptip"].ToString();//14.17.77.85:6112
            string bkptport = dt.Rows[0]["bkptport"].ToString();//14.17.77.85:6112
            return bkptip + ":" + bkptport;
        }


    }
}
